package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import server.controller.ActiveSessions;
import server.controller.Broadcaster;
import server.controller.ClientSession;
import server.controller.OutboundMessages;
import server.game.GameClientCombiner;
import server.util.Logger;
import shared.util.Config;

/**
 * The Class ServerMain
 * used to start the server.
 */
public class ServerMain {
	
	/** The port which will be used to create a server socket. */
	private static int PORT;
	
	public static void main(String[] args) throws IOException {
		Logger logger = new Logger();
		Config config = new Config("config.xml", logger);
		PORT = config.getPort();
		ActiveSessions activeSessions = new ActiveSessions(logger);
		OutboundMessages outQueue = new OutboundMessages(logger);

		ServerSocket serv = new ServerSocket(PORT);
		
		new Broadcaster(activeSessions, outQueue);
		new GameClientCombiner(activeSessions, outQueue, logger, config);

		try {
			while (true) { 									
				Socket sock = serv.accept(); 
				try {
					new ClientSession(sock, activeSessions, logger);
				} catch (IOException e) {
					logger.logError("Socket error.");
					sock.close();
				}
			} 

		} finally {
			logger.log("Server closed.");
			serv.close();
			logger.close();
		}
	}
}